package ua.lk.phonebook.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;

import ua.lk.phonebook.Database;
import ua.lk.phonebook.model.Permissions;
import ua.lk.phonebook.model.User;
import ua.lk.utils.StringUtils;


public class UserDao {
	private static String PASSKEY = "abyRvalG";
	private static String USER_SELECT = 
			"select user_id, username,  department_id, department, login, password, enabled, "
			+ "roles_text, startdate, enddate from view_users_list";

	private static String PERMISSIONS_SELECT =
			"select a.user_id, a.permission_id, b.code from view_user_permissions a " +
			"left join users_permissions b on a.permission_id = b.id where a.user_id = ";
	
	private Connection conn;
	public UserDao()
	{
		conn = Database.getConnection();
	}
	
	public void closeConnection()
	{
		if( conn != null)
		{
			Database.close(conn);
			conn = null;
		}
	}
	
	public User getUserByLogin(String login)
	{
		return getUser("login", login );
	}

	public User getUserByID(String userid)
	{
		return getUser("user_id", userid );
	}
	
	public User getUser(String fieldname, String value)
	{
		PreparedStatement pst = null;
		User user = null;
		try {
			pst = conn.prepareStatement(USER_SELECT+" where "+fieldname+"=?");
			pst.setString(1, value);
			ResultSet rs = pst.executeQuery();
			user = getUser(rs);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			Database.close(pst);
		}
		return user;		
	}
	
	public List<User> getUsers(String filter)
	{
		List<User> users = new ArrayList<User>();
		Statement st = null;
		try 
		{
			st = conn.createStatement();			
			ResultSet rs = st.executeQuery(USER_SELECT+filter);
			User user;
			do {
				user = getUser(rs);
				if(user != null)
					users.add(user);
			} while (user != null);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			Database.close(st);
		}
		
		return users;
	}

	private User getUser( ResultSet rs )
	{
		User user = null;
		try 
		{
			if(rs.next())
			{
				user = new User();
				user.setDepartment(rs.getString("department"));
				user.setDepartmentId(rs.getInt("department_id"));
				user.setEnabled(rs.getBoolean("enabled"));
				user.setEndDate(rs.getDate("enddate"));
				user.setStartDate(rs.getDate("startdate"));
				user.setLogin(rs.getString("login"));
				user.setPassword(StringUtils.decrypt(rs.getString("password"), PASSKEY));
				user.setUserId(rs.getInt("user_id"));
				user.setUsername(rs.getString("username"));
				user.setRoles_text(rs.getString("roles_text"));
				getPermissions(user.getPermissions(), user.getUserId());
			}
		}
		catch( Exception e )
		{
			e.printStackTrace();
		}
		return user;
	}
	
	private void getPermissions(EnumSet<Permissions> perm, int userID)
	{
		Statement st = null;
		try 
		{
			st = conn.createStatement();			
			ResultSet rs = st.executeQuery(PERMISSIONS_SELECT + userID);
			perm.clear();
			while(rs.next())
				perm.add(Permissions.valueOf(rs.getString("code")));
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			Database.close(st);
		}
		
	}
	
	/**
	 * 
	 * @param username 
	 * @param password 
	 * @return User object model or NULL if user and password has not found
	 */
	public User checkUserPassword(String username, String password)
	{
		User user = getUserByLogin(username);
		if(user != null && password.equals(user.getPassword()))
			return user;
		else
			return null;
	
	}
	
	// public 
}
